import dd from 'dingtalk-jsapi';
import qs from 'qs';
import apis from './apis';
import store from '../store';
import env from 'dingtalk-javascript-env';

export function getUrlParam () {
  const search = window.location.search.replace('?', '');
  return qs.parse(search);
}

class DingClient {
  static config = {
    agentId: '',
    corpId: ''
  }

  // 钉钉授权
  static _auth () {
    return new Promise((resolve, reject) => {
      const url = window.location.href.split('#')[0];
      const params = {
        url
      };
      apis.getJsApi(params).then(res => {
        // console.log('-----------getJsApi');
        if (res.code === 0) {
          const { result } = res;
          this.config = {
            agentId: result.agentId,
            corpId: result.corpId
          };
          dd.config({
            agentId: result.agentId,
            corpId: result.corpId,
            timeStamp: result.timeStamp,
            nonceStr: result.nonceStr,
            signature: result.signature,
            jsApiList: [
              'runtime.info',
              'biz.contact.complexPicker',
              'biz.contact.choose',
              'biz.contact.departmentsPicker'
            ]
          });
          dd.error(function (err) {
            console.log('钉钉error', err);
          });
          resolve({ success: true });
        }
      }).catch(err => {
        reject(new Error({ success: false, msg: err }));
      });
    });
  }

  // 选择部门
  static chooseDepartment (options = { multiple: true, pickedDepartments: [], requiredDepartments: [], disabledDepartments: [] }) {
    const { multiple, pickedDepartments, requiredDepartments, disabledDepartments } = options;
    return new Promise((resolve, reject) => {
      this._auth().then(() => {
        const { config } = this;
        dd.ready(function () {
          console.log('钉钉 ready', config.agentId, config.corpId);
          dd.biz.contact.departmentsPicker({
            title: '请选择部门', // 标题
            corpId: config.corpId, // 企业的corpId
            multiple, // 是否多选
            limitTips: '超出了', // 超过限定人数返回提示
            maxDepartments: 100, // 最大选择部门数量
            pickedDepartments, // 已选部门
            disabledDepartments, // 不可选部门
            requiredDepartments, // 必选部门（不可取消选中状态）
            appId: config.agentId, // 微应用的Id
            permissionType: 'GLOBAL', // 选人权限，目前只有GLOBAL这个参数
            onSuccess: function (result) {
              /**
                {
                    userCount:1,                              //选择人数
                    departmentsCount:1，//选择的部门数量
                    departments:[{"id":,"name":"","number":}]//返回已选部门列表，列表中每个对象包含id（部门id）、name（部门名称）、number（部门人数）
                }
                */
              console.log(result, '选择部门成功');
              resolve(result);
            },
            onFail: function (err) {
              console.log(err, '选择部门失败');
              reject(err);
            }
          });
        });
      });
    });
  }

  // 选择人
  static choosePeople (options = { multiple: true, users: [] }) {
    const { multiple, users } = options;
    return new Promise((resolve, reject) => {
      this._auth().then(() => {
        const { config } = this;
        dd.ready(function () {
          dd.biz.contact.choose({
            multiple, // 是否多选：true多选 false单选； 默认true
            users, // 默认选中的用户列表，员工userid；成功回调中应包含该信息
            corpId: config.corpId, // 企业id
            max: 100, // 人数限制，当multiple为true才生效，可选范围1-1500
            onSuccess: function (data) {
              /* data结构
                [{
                  "name": "张三", //姓名
                  "avatar": "http://g.alicdn.com/avatar/zhangsan.png" //头像图片url，可能为空
                  "emplId": '0573', //员工userid
                },
                ...
                ]
              */
              resolve(data);
              console.log(data, '选择人成功');
            },
            onFail: function (err) {
              reject(err);
              console.log(err, '选择人失败');
            }
          });
        });
      });
    });
  }

  static login () {
    const isDD = env.isDingTalk;
    return new Promise((resolve, reject) => {
      if (isDD) {
        this._loginByDD().then(() => {
          resolve(true);
        }).catch(err => reject(err));
      } else {
        this._loginByURL().then(() => {
          resolve(true);
        }).catch(err => reject(err));
      }
    });
  }

  static _loginByDD () {
    const _this = this;
    const url = window.location.href.split('#')[0];
    const { corpid } = getUrlParam();
    return new Promise((resolve, reject) => {
      dd.ready(() => {
        dd.runtime.permission.requestAuthCode({
          corpId: corpid,
          onSuccess: (res) => {
            const payload = {
              code: res.code,
              corp_id: corpid,
              url
            };
            _this._fetchToken(payload).then(() => resolve(true)).catch(err => reject(err));
          },
          onFail: (error) => {
            _this.$message({ message: '登陆失败！', type: 'warning', center: true });
            reject(error);
          }
        });
      });
    });
  }

  static _loginByURL () {
    return new Promise((resolve, reject) => {
      const { code, corpid } = getUrlParam();
      const url = window.location.href.split('#')[0];
      const payload = {
        code,
        corp_id: corpid,
        url
      };
      this._fetchToken(payload).then(() => resolve(true)).catch(err => reject(err));
    });
  }

  static _fetchToken (params) {
    return new Promise((resolve, reject) => {
      store.dispatch('user/getUserInfo', params).then(() => {
        resolve(true);
      }).catch(err => reject(err));
    });
  }

  static install (Vue) {
    Vue.prototype.$dd = this;
  }
}

export default DingClient;
